﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Biosek
{
	public static class NumericCsvHelper
	{
		public static T[][] LoadPlain<T>(string filename, char delimiter = ',') where T : struct
		{
			var list = new List<T[]>();
			using (var reader = new StreamReader(filename))
			{
				while (!reader.EndOfStream)
				{
					var line = reader.ReadLine();
					var numbers = line
						.Split(delimiter)
						.Select(x => x.Trim())
						.Select(x => (T)Convert.ChangeType(x, typeof(T)));
					list.Add(numbers.ToArray());
				}
			}
			return list.ToArray();
		}

		/// <summary>
		/// Almacena un archivo en formato CSV numerico
		/// </summary>
		/// <typeparam name="T">Tipo de dato usado, debe ser un tipo entero</typeparam>
		/// <param name="filename">Archivo a ser guardado</param>
		/// <param name="data">Secuencias</param>
		public static void SavePlain<T>(string filename, IEnumerable<IEnumerable<T>> data, char delimiter = ',') where T : struct
		{
			using (var writer = new StreamWriter(filename))
			{
				foreach (var row in data)
				{
					var strs = row.Select(x => Convert.ChangeType(x, TypeCode.Int32).ToString());
					var line = string.Join(delimiter.ToString(), strs);
					writer.WriteLine(line);
				}
				writer.Close();
			}
		}
	}
}
